from django.shortcuts import render
from django.http import HttpResponse
from .models import *
from openpyxl import load_workbook
import glob
from .info_down import DownToDjango

# Create your views here.

def index(request):

    context = {}

    return render(request,'script/index.html',context)

def script_contrast(request):

    if glob.glob('script/script/contrast_list_已经导入数据库存.txt'):

        return HttpResponse('已经导入数据库存')

    
    wb = load_workbook('script/script/contrast_list.xlsx')

    sheet = wb['清单-6484']

    info = [Contrast(book_name = i[0].value,
                     book_author = i[1].value ) \
            for i in zip(sheet['A'],sheet['B'])]

    Contrast.objects.bulk_create(info)

    with open('script/script/contrast_list_已经导入数据库存.txt','w') as f:

        f.write('已经导入数据库存')

    

    return HttpResponse('写入完成')

def book_to_db(request,key1,key2):

    if not glob.glob('script/script/book_to_db_类型{}.txt'.format(key1)):

        with open('script/script/book_to_db_类型{}.txt'.format(key1),'w') as f:
            f.write('正在执行中......')        
    
        
        DownToDjango(key1,key2).my_thread()

        with open('script/script/book_to_db_类型{}.txt'.format(key1),'w') as f:

            f.write('执行完毕')

        

        return HttpResponse('类型：{}，已经导入数据库存'.format(key1))

    
    elif glob.glob('script/script/book_to_db_类型{}.txt'.format(key1)):

        with open('script/script/book_to_db_类型{}.txt'.format(key1)) as f:
            info = f.read()
        
        return HttpResponse('类型：{},{}'.format(key1,info))
    
        
    





























    
